var tid = null;
var question_content = null;
var question_content_all = null;
var answerList = null;
var commentList_all = null;
var answer_remind_count = 0;
var comment_remind_count = 0;
$(function () {
    onloadTitleContext();

    $("input[name='qid']").val(GetQueryString("qid"));

    changeSearchInput();


    /*查询所有的话题*/
    $.ajax({
        url: "/topic/selectAll",
        dataType: "json",
        success: function (result) {
            var topicList = result.topicList;
            for (var i = 0; i < 4; i++) {
                var str = '<button class="flag">' + topicList[i].title + '</button>';
                $("#flag_context").append(str);
            }
        }
    });

    /*summernote富文本编辑器配置，上传文件*/
    $("#summernote").summernote({
        height: 500,
        callbacks: {
            onImageUpload: function (files) {
                var formData = new FormData();
                formData.append('file', files[0]);
                $.ajax({
                    url: '/answer/uploadImage',//后台文件上传接口
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        $('#summernote').summernote('insertImage', data, 'img');
                    }
                });
            }
        }
    });

    /*提交回答*/
    $("#add_btn").click(function () {
        $("#add_btn").prop("disabled", true);
        $("#addAnswerForm").ajaxSubmit({
            dataType: "json",
            success: function (result) {
                $("#add_btn").prop("disabled", false);
                if (result) {
                    $("#add_answer_modal").modal("hide");
                    $("#addAnswerForm").resetForm();
                    $("#summernote").summernote("reset");
                    getAnswerText();
                } else {
                    $("#add_btn").prop("disabled", false);
                    $("#msg").html("提交失败~请重新提交！")
                }
            }
        })
    });

    $.ajax({
        url: "/user/getSession",
        dataType: "json",
        success: function (sessionUser) {
            $("#hand_image").prop("src", sessionUser.handimage)
        }
    });

    getAnswerText();

    removeLoading("loading");
});

/*检查页面上提醒徽章的数量，如果是 0 ，则隐藏徽章*/
function check_badge() {
    var html = $("#badge_number").html();
    if (html == 0) {
        $("#badge_number").html("");
    }
}

/*评论提醒*/
function commentRemind() {
    $("#comment_remind").html("");
    $.ajax({
        url: "/remind/commentRemind",
        dataType: "json",
        async: false,
        success: function (result) {
            var remindList = result.rows;
            comment_remind_count = remindList.length;
            $("#badge_number").html(comment_remind_count + answer_remind_count);
            check_badge();
            for (var i = 0; i < remindList.length; i++) {
                var str = '<tr>\n' +
                    '       <td style="width: 90%">\n' +
                    '           <a href="#">' + remindList[i].user.username + '</a>\n' +
                    '               评论了你的\n' +
                    '           <a href="answer_show.html?qid=' + remindList[i].question.id + '">' + remindList[i].question.title + '</a>\n' +
                    '               问题上的回答\n' +
                    '       </td>\n' +
                    '       <td>\n' +
                    '           <button id="comment_read_btn_' + remindList[i].comment.id + '" onclick="commentRedmindRead(' + remindList[i].comment.id + ')" class="btn btn-default">标记已读</button>\n' +
                    '       </td>\n' +
                    '      </tr>';
                $("#comment_remind").append(str);
            }
        }
    })
}

/*评论提醒标记已读*/
function commentRedmindRead(cid) {
    $("#comment_read_btn_" + cid).prop("hidden", true);
    commentRedmindRead_ajax(cid);
}

/*评论提醒标记已读异步请求*/
function commentRedmindRead_ajax(cid) {
    $.ajax({
        url: "/remind/readCommentRemind?cid=" + cid,
        dataType: "json",
        async: false,
        success: function (result) {
            if (result) {
                commentRemind();
            }
        }
    })
}

/*回答提醒*/
function remindModal() {
    $("#answer_remind").html("");
    $.ajax({
        url: "/remind/answerRemind",
        dataType: "json",
        async: false,
        success: function (result) {
            var remindList = result.rows;
            answer_remind_count = remindList.length;
            $("#badge_number").html(answer_remind_count + comment_remind_count);
            check_badge();
            for (var i = 0; i < remindList.length; i++) {
                var str = '<tr>\n' +
                    '       <td style="width: 90%">\n' +
                    '           <a href="#">' + remindList[i].answerUser.username + '</a>\n' +
                    '               回答了你的\n' +
                    '           <a href="answer_show.html?qid=' + remindList[i].answerQuestion.id + '">' + remindList[i].answerQuestion.title + '</a>\n' +
                    '               问题\n' +
                    '       </td>\n' +
                    '       <td>\n' +
                    '           <button id="read_btn_' + remindList[i].answer.id + '" class="btn btn-default" onclick="remindRead(' + remindList[i].answer.id + ')">标记已读</button>\n' +
                    '       </td>\n' +
                    '      </tr>';
                $("#answer_remind").append(str);
            }
        }
    })
}

/*回答提醒标记*/
function remindRead(aid) {
    $("#read_btn_" + aid).prop("hidden", true);
    remindRead_ajax(aid);
}

/*回答提醒标记异步请求*/
function remindRead_ajax(aid) {
    $.ajax({
        url: "/remind/readRemind?aid=" + aid,
        dataType: "json",
        async: false,
        success: function (result) {
            if (result) {
                remindModal();
            }
        }
    })
}

function setFollowBtn() {
    $("#cancel_follow_question_btn").prop("class", "btn btn-primary hidden");
    $("#follow_question_btn").prop("class", "btn btn-primary hidden");
}

function select_relevat_question() {
    $("#relevant_question").html("");
    $.ajax({
        url: "/question/findByTid?tid=" + tid,
        dataType: "json",
        success: function (result) {
            var questionList = result.rows;
            if (questionList.length > 5) {
                for (var i = 0; i < 5; i++) {
                    var str1 = '<a href=answer_show.html?qid=' + questionList[i].id + '>' +
                        '' + questionList[i].title + '' +
                        '</a>' +
                        '<span>84 个回答</span>' +
                        '<br>';
                    $("#relevant_question").append(str1);
                }
            } else {
                for (var i = 0; i < questionList.length; i++) {
                    var str2 = '<a href=answer_show.html?qid=' + questionList[i].id + '>' +
                        '' + questionList[i].title + '' +
                        '</a>' +
                        '<span>84 个回答</span>' +
                        '<br>';
                    $("#relevant_question").append(str2);
                }
            }
        }
    });
}

function onloadTitleContext() {
    setFollowBtn();
    $.ajax({
        url: "/question/findById?id=" + GetQueryString("qid"),
        type: "get",
        dataType: "json",
        async: true,
        success: function (result) {
            var question = result.rows;
            tid = question.tid;
            select_relevat_question();
            $("#title_b").html(question.title);
            $("title").html(question.title);
            if (question.synopsis.length > 70) {
                question_content_all = question.synopsis;
                question_content = question.synopsis.substr(0, 70) + " ...";
                $("#content").html(question_content);
                $("#content").append('<button class="show_All_btn" onclick="showAll()">显示全部 <span class="glyphicon glyphicon-chevron-down"></span></button>')
            } else {
                $("#content").html(question.synopsis);
            }
            checkFollowQuestionBtn();
        }
    });
}

function checkFollowQuestionBtn() {
    $.ajax({
        url: "/user/getSession",
        dataType: "json",
        async: false,
        success: function (user) {
            $.ajax({
                url: "/followQuestion/getFollowInfo?uid=" + user.id + "&qid=" + GetQueryString("qid"),
                dataType: "json",
                async: false,
                success: function (result) {
                    if (result) {
                        var prop = $("#cancel_follow_question_btn").prop("class");
                        var strings = prop.split(" ");
                        var str = "";
                        for (var i = 0; i < strings.length - 1; i++) {
                            str += strings[i];
                            str += " ";
                        }
                        $("#cancel_follow_question_btn").prop("class", str);
                    } else {
                        var prop = $("#follow_question_btn").prop("class");
                        var strings = prop.split(" ");
                        var str = "";
                        for (var i = 0; i < strings.length - 1; i++) {
                            str += strings[i];
                            str += " ";
                        }
                        $("#follow_question_btn").prop("class", str);
                    }
                }
            })
        }
    })
}

/*获取回答的信息*/
function getAnswerText() {
    $.ajax({
        url: "/answer/findAllByQid?qid=" + GetQueryString("qid"),
        dataType: "json",
        async: false,
        success: function (result) {
            $("#answer_area").html("");
            var rows = result.rows;
            answerList = rows;
            for (var i = 0; i < rows.length; i++) {
                var user = userInfo(rows[i].uid);
                var commentCount = getCommentCountByAid(rows[i].id);
                var str = '<div class="col-md-12 answer_one">' +
                    '           <div class="col-md-12" style="padding: 0">\n' +
                    '                <div class="col-md-2">\n' +
                    '                    <img style="width: 50px;height: 50px" class="center-block"\n' +
                    '                         src="' + user.handimage + '">\n' +
                    '                </div>\n' +
                    '                <div class="col-md-10" style="padding: 0">\n' +
                    '                    <span><b>' + user.username + '</b></span>\n' +
                    '                    <br>\n' +
                    '                    <span>间歇性踌躇满珠 持续性混吃等死</span>\n' +
                    '                </div>\n' +
                    '            </div>\n' +
                    '            <div class="col-md-12">\n' +
                    '                <span class="answer_good_number_context">23人赞同了该回答</span>\n' +
                    '            </div>\n' +
                    '            <div class="col-md-12">\n' +
                    '                <div id="context_area">' + rows[i].content + '</div>\n' +
                    '            </div>\n' +
                    '            <div class="col-md-12">\n' +
                    '                <span class="answer_good_number_context">编辑于 2018-10-04</span>\n' +
                    '            </div>\n' +
                    '            <div class="col-md-12" style="padding: 0">\n' +
                    '                <div class="bottom">\n' +
                    '                    <button id="answer_good_btn_' + rows[i].id + '" onclick="answer_good(' + rows[i].id + ')" class="btn good_btn" disabled><span class="glyphicon glyphicon-thumbs-up"></span> 赞同 1.5k</button>\n' +
                    '                    <button id="answer_cancel_good_btn_' + rows[i].id + '" onclick="answer_cancel_good(' + rows[i].id + ')" class="btn good_btn" disabled><span class="glyphicon glyphicon-thumbs-down"></span></button>\n' +
                    '                    <button id="show_comment_' + rows[i].id + '" onclick="showComment(' + rows[i].id + ')" class="bottom_context" href="#"><span class="glyphicon glyphicon-comment"></span> ' + commentCount + ' 条评论</button>\n' +
                    '                    <button id="comment_up_' + rows[i].id + '" onclick="comment_up(' + rows[i].id + ')" class="bottom_context" hidden>收起评论</button>' +
                    '                    <button class="bottom_context"><span class="glyphicon glyphicon-send"></span> 分享</button>\n' +
                    '                    <button class="bottom_context"><span class="glyphicon glyphicon-star"></span> 收藏</button>\n' +
                    '                    <button class="bottom_context"><span class="glyphicon glyphicon-heart"></span> 感谢</button>\n' +
                    '                    <button hidden id="answer_del_btn_' + rows[i].id + '" class="bottom_context" onclick="deleteAnswer(' + rows[i].id + ')"><span class="glyphicon glyphicon-trash"></span></button>\n' +
                    '                </div>\n' +
                    '            </div>' +
                    '            <div id="answer' + rows[i].id + '" class="col-md-12 head_div" hidden>\n' +
                    '                <div class="col-md-6"><span><strong>' + commentCount + '条评论</strong></span></div>\n' +
                    '                <div class="col-md-6">\n' +
                    '                   <button class="nullStyle_btn pull-right"><span class="glyphicon glyphicon-refresh"> 切换为时间排序</span></button>\n' +
                    '                </div>' +
                    '                <div id="comment' + rows[i].id + '" class="col-md-12"></div>' +
                    '                <div class="col-md-12">' +
                    '                   <form id="comment_form_' + rows[i].id + '" class="form-group form-inline" action="/comment/add" method="post">' +
                    '                       <input class="form-control" type="text" name="content"/>' +
                    '                       <input type="hidden" name="aid" value="' + rows[i].id + '">' +
                    '                       <button onclick="submit_comment_form(' + rows[i].id + ')" class="btn btn-default">评论</button>' +
                    '                   </form>' +
                    '               </div>' +
                    '           </div>' +
                    '       </div>';
                $("#answer_area").append(str);
            }
        }
    });
    checkAnswerDeleteBtn();
    checkAnswerGoodBtn();
    remindModal();
    commentRemind();
}

/*回答点赞*/
function answer_good(aid) {
    loading();
    $.ajax({
        url: "/answerGood/good?aid=" + aid,
        dataType: "json",
        success: function () {
            getAnswerText();
            removeLoading("loading");
        }
    })
}

/*回答取消点赞*/
function answer_cancel_good(aid) {
    loading();
    $.ajax({
        url: "/answerGood/cancelGood?aid=" + aid,
        dataType: "json",
        success: function () {
            getAnswerText();
            removeLoading("loading");
        }
    })
}

/*检查回答点赞的按钮样式*/
function checkAnswerGoodBtn() {
    for (var i = 0; i < answerList.length; i++) {
        $.ajax({
            url: "/answerGood/findByUidAid?aid=" + answerList[i].id,
            dataType: "json",
            async: false,
            success: function (result) {
                if (result) {
                    $("#answer_cancel_good_btn_" + answerList[i].id).prop("disabled", false);
                } else {
                    $("#answer_good_btn_" + answerList[i].id).prop("disabled", false);
                }
                $.ajax({
                    url: "/answerGood/selectCount?aid=" + answerList[i].id,
                    dataType: "json",
                    async: false,
                    success: function (result) {
                        $("#answer_good_btn_" + answerList[i].id).html("赞同 " + result + " 人");
                    }
                })
            }
        })
    }
}

/*提交评论表单*/
function submit_comment_form(aid) {
    loading();
    $("#comment_form_" + aid).ajaxSubmit();
    getAnswerText();
    removeLoading("loading");
}

/*检查回答删除按钮*/
function checkAnswerDeleteBtn() {
    $.ajax({
        url: "/user/getSession",
        dataType: "json",
        success: function (user) {
            for (var i = 0; i < answerList.length; i++) {
                if (answerList[i].uid == user.id) {
                    $("#answer_del_btn_" + answerList[i].id).prop("hidden", false);
                }
            }
        }
    })
}

function userInfo(uid) {
    var user = null;
    $.ajax({
        url: "/user/findById?id=" + uid,
        dataType: "json",
        async: false,
        success: function (result) {
            user = result;
        }
    })
    ;
    return user;
}

function GetQueryString(name) {

    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");

    var r = window.location.search.substr(1).match(reg);

    if (r != null) return unescape(r[2]);
    return null;
}

function changeSearchInput() {
    setInterval(function () {
        $.ajax({
            url: "/question/list",
            dataType: "json",
            success: function (result) {
                var questionList = result.rows;
                var randomNumber = GetRandomNum(0, questionList.length - 1);
                $("#search_input").prop("placeholder", questionList[randomNumber].title);
            }
        });
    }, 5000);

}

// 获取最小值到最大值之前的整数随机数
function GetRandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return (Min + Math.round(Rand * Range));
}

function showAll() {
    $("#middle_div").css("height", "");
    $("#content").html(question_content_all);
    $("#up_btn").prop("hidden", false);
}

function hiddenQuestionContent() {
    $("#content").html(question_content);
    $("#content").append('<button class="show_All_btn" onclick="showAll()">显示全部 <span class="glyphicon glyphicon-chevron-down"></span></button>');
    $("#up_btn").prop("hidden", true);
}

/*展示评论*/
function showComment(aid) {
    loading();
    $("#comment" + aid).html("");
    $("#answer" + aid).prop("hidden", false);
    $("#show_comment_" + aid).prop("hidden", true);
    $("#comment_up_" + aid).prop("hidden", false);
    $.ajax({
        url: "/comment/findByAid?aid=" + aid,
        dataType: "json",
        async: false,
        success: function (result) {
            var commentList = result.rows;
            commentList_all = commentList;
            for (var i = 0; i < commentList.length; i++) {
                var user = userInfo(commentList[i].uid);
                var str = '<div class="col-md-12 comment_one">\n' +
                    '        <div class="col-md-6">\n' +
                    '            <img style="width: 1.5em" src="' + user.handimage + '">\n' +
                    '            <span>' + user.username + '</span>\n' +
                    '        </div>\n' +
                    '        <div class="col-md-6">\n' +
                    '            <button id="comment_del_btn_' + commentList[i].id + '" class="btn btn-danger btn-xs pull-right" disabled onclick="deleteComment(' + commentList[i].id + ')">' +
                    '               <span class="glyphicon glyphicon-trash"></span>' +
                    '            </button>\n' +
                    '        </div>\n' +
                    '        <div class="col-md-12">' + commentList[i].content + '</div>\n' +
                    '        <div class="col-md-12">\n' +
                    '            <button hidden onclick="comment_good(' + commentList[i].id + ',' + aid + ')" id="comment_good_btn_' + commentList[i].id + '" class="nullStyle_btn"><span class="glyphicon glyphicon-thumbs-up"></span> ' +
                    '               <span id="comment_good_img_' + commentList[i].id + '">000</span>' +
                    '            </button>\n' +
                    '            <button hidden onclick="comment_cancel_good(' + commentList[i].id + ',' + aid + ')" id="comment_cancel_good_btn_' + commentList[i].id + '" class="nullStyle_btn"><span class="glyphicon glyphicon-thumbs-down"></span>' +
                    '               <span id="comment_cancel_good_img_' + commentList[i].id + '">000</span>' +
                    '            </button>' +
                    '        </div>\n' +
                    '    </div>';
                $("#comment" + aid).append(str);
            }
        }
    })
    checkCommentBtn();
    checkCommentGoodBtn();
    commentGoodCount();
    removeLoading("loading");
}

function comment_cancel_good(cid, aid) {
    loading();
    $.ajax({
        url: "/commentGood/cancelGood?cid=" + cid,
        dataType: "json",
        success: function () {
            showComment(aid);
            removeLoading("loading");
        }
    })
}

function comment_good(cid, aid) {
    loading();
    $.ajax({
        url: "/commentGood/good?cid=" + cid,
        dataType: "json",
        success: function () {
            showComment(aid);
            removeLoading("loading");
        }
    })
}

function commentGoodCount() {
    for (var i = 0; i < commentList_all.length; i++) {
        var flag = i;
        $.ajax({
            url: "/commentGood/goodCountByCid?cid=" + commentList_all[i].id,
            dataType: "json",
            async: false,
            success: function (result) {
                $("#comment_good_img_" + commentList_all[i].id).html(result);
                $("#comment_cancel_good_img_" + commentList_all[i].id).html(result);
            }
        })
    }
}

function checkCommentGoodBtn() {
    for (var i = 0; i < commentList_all.length; i++) {
        $.ajax({
            url: "/commentGood/findByUidCid?cid=" + commentList_all[i].id,
            dataType: "json",
            async: false,
            success: function (result) {
                console.log(result);
                if (result) {
                    $("#comment_cancel_good_btn_" + commentList_all[i].id).prop("hidden", false);
                } else {
                    $("#comment_good_btn_" + commentList_all[i].id).prop("hidden", false);
                }
            }
        })
    }
}

function checkCommentBtn() {
    $.ajax({
        url: "/user/getSession",
        dataType: "json",
        success: function (user) {
            for (var i = 0; i < commentList_all.length; i++) {
                if (commentList_all[i].uid == user.id) {
                    $("#comment_del_btn_" + commentList_all[i].id).prop("disabled", false);
                }
            }
        }
    })
}

function comment_up(aid) {
    $("#comment_up_" + aid).prop("hidden", true);
    $("#show_comment_" + aid).prop("hidden", false);
    $("#answer" + aid).prop("hidden", true);
    $("#comment" + aid).html("");
}

function getCommentCountByAid(aid) {
    var commentCount = null;
    $.ajax({
        url: "/comment/getCountByAid?aid=" + aid,
        dataType: "json",
        async: false,
        success: function (count) {
            if (count == null) {
                commentCount = 0;
            } else {
                commentCount = count;
            }
        }
    })
    return commentCount;
}

function deleteAnswer(aid) {
    $.ajax({
        url: "/answer/delete?id=" + aid,
        dataType: "json",
        success: function (result) {
            if (result) {
                alert("删除成功！");
                getAnswerText();
            } else {
                alert("删除失败！");
                getAnswerText();
            }
        }
    })
}

function deleteComment(cid) {
    $.ajax({
        url: "/comment/delete?id=" + cid,
        dataType: "json",
        async: false,
        success: function (result) {
            if (result) {
                alert("删除成功！");
                getAnswerText();
            } else {
                alert("删除失败！");
                getAnswerText();
            }
        }
    })
}

function follow_question() {
    $.ajax({
        url: "/followQuestion/question?qid=" + GetQueryString("qid"),
        dataType: "json",
        success: function (result) {
            if (result) {
                alert("关注成功！");
                onloadTitleContext();
            } else {
                alert("关注失败！");
            }
        }
    })
}

function cancel_follow_question() {
    $.ajax({
        url: "/followQuestion/cancelQuestion?qid=" + GetQueryString("qid"),
        dataType: "json",
        success: function (result) {
            if (result) {
                alert("操作成功！");
                onloadTitleContext();
            } else {
                alert("操作失败！");
            }
        }
    })
}

function loading() {
    $('body').loading({
        loadingWidth: 240,
        title: '请稍等!',
        name: 'loading',
        discription: '马上就好哦~',
        direction: 'column',
        type: 'origin',
        // originBg:'#71EA71',
        originDivWidth: 40,
        originDivHeight: 40,
        originWidth: 6,
        originHeight: 6,
        smallLoading: false,
        loadingMaskBg: 'rgba(0,0,0,0.2)',
    });

}

function logout() {
    $.ajax({
        url: "/user/loginOutput",
        dataType: "json",
        success: function (result) {
            if (result) {
                alert("注销成功！");
                location.href = "/login.html";
            } else {
                alert("注销失败！");
            }
        }
    })
}